<template>
  <div class="notification-center">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card class="notification-summary">
          <template #header>
            <div class="card-header">
              <span>通知概览</span>
              <el-button type="primary" @click="refreshData">刷新</el-button>
            </div>
          </template>

          <div class="summary-content">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="summary-item">
                  <div class="item-icon" style="background-color: #f56c6c;">
                    <el-icon><Bell /></el-icon>
                  </div>
                  <div class="item-info">
                    <div class="item-value">{{ unreadCount }}</div>
                    <div class="item-label">未读通知</div>
                  </div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="summary-item">
                  <div class="item-icon" style="background-color: #409eff;">
                    <el-icon><Notification /></el-icon>
                  </div>
                  <div class="item-info">
                    <div class="item-value">{{ totalCount }}</div>
                    <div class="item-label">总通知数</div>
                  </div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="summary-item">
                  <div class="item-icon" style="background-color: #67c23a;">
                    <el-icon><BellFilled /></el-icon>
                  </div>
                  <div class="item-info">
                    <div class="item-value">{{ announcementCount }}</div>
                    <div class="item-label">公告数量</div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>

        <el-card class="recent-notifications">
          <template #header>
            <div class="card-header">
              <span>最近通知</span>
              <el-button link type="primary" @click="goToNotificationList">查看更多</el-button>
            </div>
          </template>

          <div class="notifications-list">
            <div
              v-for="notification in recentNotifications"
              :key="notification.id"
              class="notification-item"
              :class="{ 'unread': !notification.isRead }"
            >
              <div class="item-header">
                <el-tag
                  :type="getNotificationTypeTag(notification.type)"
                  effect="plain"
                  size="small"
                >
                  {{ formatNotificationType(notification.type) }}
                </el-tag>
                <span class="item-time">{{ formatTime(notification.createdAt) }}</span>
              </div>
              <div class="item-title">{{ notification.title }}</div>
              <div class="item-content">{{ notification.content }}</div>
              <div class="item-actions">
                <el-button
                  v-if="!notification.isRead"
                  size="small"
                  type="primary"
                  @click="markAsRead(notification)"
                >
                  标为已读
                </el-button>
                <el-button
                  size="small"
                  @click="viewDetail(notification)"
                  v-if="notification.link"
                >
                  查看详情
                </el-button>
              </div>
            </div>

            <div v-if="recentNotifications.length === 0" class="empty">
              暂无通知
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="announcement-summary">
          <template #header>
            <div class="card-header">
              <span>最新公告</span>
              <el-button link type="primary" @click="goToAnnouncementList">查看更多</el-button>
            </div>
          </template>

          <div class="announcements-list">
            <div
              v-for="announcement in recentAnnouncements"
              :key="announcement.id"
              class="announcement-item"
            >
              <div class="item-header">
                <el-tag
                  :type="getAnnouncementTypeTag(announcement.type)"
                  size="small"
                >
                  {{ formatAnnouncementType(announcement.type) }}
                </el-tag>
                <el-tag
                  v-if="announcement.isTop"
                  type="danger"
                  size="small"
                  effect="dark"
                >
                  置顶
                </el-tag>
              </div>
              <div class="item-title">{{ announcement.title }}</div>
              <div class="item-meta">
                <span>{{ formatTime(announcement.publishAt || announcement.createdAt) }}</span>
                <span>浏览: {{ announcement.viewCount }}</span>
              </div>
            </div>

            <div v-if="recentAnnouncements.length === 0" class="empty">
              暂无公告
            </div>
          </div>
        </el-card>

        <el-card class="quick-actions">
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
            </div>
          </template>

          <div class="actions-grid">
            <div class="action-item" @click="goToNotificationList">
              <div class="item-icon" style="background-color: #409eff;">
                <el-icon><Notification /></el-icon>
              </div>
              <div class="item-label">查看通知</div>
            </div>
            <div class="action-item" @click="goToAnnouncementList">
              <div class="item-icon" style="background-color: #67c23a;">
                <el-icon><BellFilled /></el-icon>
              </div>
              <div class="item-label">查看公告</div>
            </div>
            <div class="action-item" @click="goToSettings">
              <div class="item-icon" style="background-color: #e6a23c;">
                <el-icon><Setting /></el-icon>
              </div>
              <div class="item-label">通知设置</div>
            </div>
            <div class="action-item" @click="goToTemplateList">
              <div class="item-icon" style="background-color: #909399;">
                <el-icon><Document /></el-icon>
              </div>
              <div class="item-label">模板管理</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type {
  Notification,
  UnreadCountResponse,
  Announcement
} from '@/types/api/notification'
import { notificationApi } from '@/api/modules/notification'
import { announcementApi } from '@/api/modules/notification'

// 路由
const router = useRouter()

// 数据相关
const unreadCount = ref(0)
const totalCount = ref(0)
const announcementCount = ref(0)
const recentNotifications = ref<Notification[]>([])
const recentAnnouncements = ref<Announcement[]>([])
const isAdmin = ref(true) // 实际项目中应从用户权限获取

// 刷新数据
const refreshData = async () => {
  await Promise.all([
    getNotificationSummary(),
    getRecentNotifications(),
    getRecentAnnouncements()
  ])
}

// 获取通知概览
const getNotificationSummary = async () => {
  try {
    const res = await notificationApi.getUnreadCount()
    const data = res.data.data
    unreadCount.value = data.total
    totalCount.value = data.total + 10 // 这里需要获取总数量，暂时用未读数+10代替
  } catch (error) {
    console.error('获取通知概览失败')
  }
}

// 获取最近通知
const getRecentNotifications = async () => {
  try {
    const res = await notificationApi.getNotificationList({
      page: 1,
      pageSize: 5
    })
    recentNotifications.value = res.data.data.list
    totalCount.value = res.data.data.total
  } catch (error) {
    console.error('获取最近通知失败')
  }
}

// 获取最近公告
const getRecentAnnouncements = async () => {
  try {
    const res = await announcementApi.getAnnouncementList({
      page: 1,
      pageSize: 5
    })
    recentAnnouncements.value = res.data.data.list
    announcementCount.value = res.data.data.total
  } catch (error) {
    console.error('获取最近公告失败')
  }
}

// 标为已读
const markAsRead = async (notification: Notification) => {
  try {
    await notificationApi.markAsRead(notification.id)
    ElMessage.success('标记成功')
    refreshData()
  } catch (error) {
    ElMessage.error('标记失败')
  }
}

// 查看详情
const viewDetail = (notification: Notification) => {
  if (notification.link) {
    window.open(notification.link, '_blank')
  }
}

// 跳转到通知列表
const goToNotificationList = () => {
  router.push('/notification/list')
}

// 跳转到公告列表
const goToAnnouncementList = () => {
  router.push('/notification/announcement')
}

// 跳转到设置页面
const goToSettings = () => {
  router.push('/notification/settings')
}

// 跳转到模板管理
const goToTemplateList = () => {
  // 模板管理页面需要管理员权限
  router.push('/notification/templates')
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 30) return `${days}天前`
  return date.toLocaleDateString()
}

// 格式化通知类型
const formatNotificationType = (type: string) => {
  const typeMap: Record<string, string> = {
    'COURSE': '课程',
    'CARD': '会员卡',
    'SYSTEM': '系统',
    'OTHER': '其他'
  }
  return typeMap[type] || type
}

// 获取通知类型标签
const getNotificationTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    'COURSE': 'success',
    'CARD': 'warning',
    'SYSTEM': 'danger',
    'OTHER': 'info'
  }
  return tagMap[type] || 'info'
}

// 格式化公告类型
const formatAnnouncementType = (type: string) => {
  const typeMap: Record<string, string> = {
    'NOTICE': '通知',
    'EVENT': '活动',
    'MAINTENANCE': '维护',
    'PROMOTION': '促销'
  }
  return typeMap[type] || type
}

// 获取公告类型标签
const getAnnouncementTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    'NOTICE': '',
    'EVENT': 'success',
    'MAINTENANCE': 'warning',
    'PROMOTION': 'danger'
  }
  return tagMap[type] || ''
}

// 生命周期
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.notification-center {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.summary-content {
  padding: 20px 0;
}

.summary-item {
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  transition: all 0.3s;
}

.summary-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.item-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.item-icon .el-icon {
  font-size: 24px;
  color: white;
}

.item-info {
  flex: 1;
}

.item-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.item-label {
  font-size: 14px;
  color: #909399;
}

.notifications-list, .announcements-list {
  max-height: 400px;
  overflow-y: auto;
}

.notification-item, .announcement-item {
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.notification-item:last-child, .announcement-item:last-child {
  border-bottom: none;
}

.notification-item.unread {
  background-color: #ecf5ff;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.item-time {
  font-size: 12px;
  color: #909399;
}

.item-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.item-content {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
  line-height: 1.5;
}

.item-actions {
  display: flex;
  gap: 10px;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.empty {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.action-item .item-icon {
  width: 40px;
  height: 40px;
  margin-right: 0;
  margin-bottom: 10px;
}

.action-item .item-label {
  font-size: 14px;
  color: #606266;
}
</style>
